package com.zoe.onelink.business.async;

import com.zoe.onelink.util.OnelinkContextHolder;
import org.slf4j.MDC;
import org.springframework.core.task.TaskDecorator;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * <p>标题: 多线程复制上下文信息</p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2019</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: chenweibin
 * @date 2019/7/25
 */
@Deprecated
public class ContextCopyingDecorator implements TaskDecorator {
    @Override
    public Runnable decorate(Runnable runnable) {
        long parentThreadId = Thread.currentThread().getId();
        Map<String, Object> map = new HashMap<>(8);
        Map<String, Object> parameterMap = OnelinkContextHolder.getCopiedMap();
        map.putAll(parameterMap);
        Map<String, String> logMap = MDC.getCopyOfContextMap();
        return () -> {
            long childThreadId = Thread.currentThread().getId();
            boolean isSameThread = Objects.equals(parentThreadId, childThreadId);
            if (!isSameThread) {
                OnelinkContextHolder.putValue(map);

                if (logMap != null) {
                    MDC.setContextMap(logMap);
                }
            }

            try {
                runnable.run();
            } finally {
                if (!isSameThread) {
                    MDC.clear();
                }
            }
        };
    }
}
